package dao

import (
	"go_server/game_server/database/mysql"
	"go_server/game_server/util"
	"go_server/zinx/zconf"
	"go_server/zinx/zlog"
	"gorm.io/gorm"
	"time"
)

type ServerInfo struct {
	ServerId int `gorm:"column:server_id;primary"`

	IdSequence int `gorm:"column:id_sequence"`

	RoleSequence int `gorm:"column:role_sequence"`

	GuildSequence int `gorm:"column:guild_sequence"`

	SysMailSequence int `gorm:"column:sys_mail_sequence"`

	RestartCount int `gorm:"column:restart_count"`

	OpenTime time.Time `gorm:"column:open_time"`

	StopTime time.Time`gorm:"column:stop_time"`
}

func (ServerInfo) TableName() string {
	return "server_info"
}

var (
	all_server_info_field = util.GetGormFields(ServerInfo{})
)
func GetServerInfoById(id int) *ServerInfo {
	db := mysql.GetServerDBConnection()
	var serverInfo ServerInfo
	if err := db.Select(all_server_info_field).Where("server_id=?", id).First(&serverInfo).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetServerInfoById ERR!!! Id: %d, err: %v", id, err)
		}
		return nil
	}

	return &serverInfo
}

func NewServerInfoData() *ServerInfo{
	serverInfo := &ServerInfo{
		ServerId: zconf.GlobalObject.Id,
		IdSequence: 0,
		RoleSequence: 0,
		GuildSequence: 0,
		SysMailSequence: 0,
		RestartCount: 0,
		OpenTime: time.Now(),
		StopTime: time.Now(),
	}
	db := mysql.GetServerDBConnection()
	if err := db.Create(serverInfo).Error; err != nil {
		zlog.Errorf("create serverInfo %v data failed: %v", serverInfo, err)
	}
	return serverInfo
}

func UpdateServerInfo(sid int, changeField *map[string]any) {
	db := mysql.GetServerDBConnection()
	if err := db.Model(ServerInfo{}).Where("server_id=?", sid).Updates(changeField).Error; err != nil {
		zlog.Errorf("update serverInfo %d data failed: %v", sid, err)
	}
}